#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os
import random
from lj_tool import lj_bean_conn, tool_haikang_v1, tool_id, tool_json, tool_log, tool_open_cv, tool_run, tool_ssh, tool_try
from lj_action import action_ai, action_fm, action_ai_remote, action_data

haikang_remote = tool_haikang_v1.initPlatDefault()

ai_record_action = action_data.init_action_data(
    "ai_record", "272ab1b9c5cc4ea2b76302238247284c")


def exe():
    pass


@tool_try.lj_no_except
def job():
    print("LJ - 开始运行AI视频分析任务...")
    # AI服务器列表
    ai_analysis_servers = action_ai.list_ai_server()
    if len(ai_analysis_servers) < 1:
        tool_log.error("LJ - 无可用AI服务器...")
        return

    # 获取监控设备列表
    camera_list = action_ai.list_camera()

    # 设备编号对应mn号关系
    mn_contrast_camera_code = {
        item.camera_code: item.mn for item in action_fm.list_mn_contrast_camera_code()}

    for item in camera_list:
        item["mn"] = mn_contrast_camera_code.get(item.get("code"))
        if not item.get("mn"):
            tool_log.error("LJ - 找不到对应设备[{item.get('code')}]的mn编号")
            continue
        # 获取视频流
        rtsp_url = haikang_remote.getStreamUrlByCameraIndexCode(
            item.get("code"), "rtsp")
        if not rtsp_url:
            continue
        # 视频流取截图
        item["capture"] = tool_open_cv.capture_frame(rtsp_url)
        item["datetime"] = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if not item.get("capture"):
            tool_log.error("LJ - 设备[{item.get('code')}]获取截图失败，可能网络波动，或者设备异常短线...")

    # 剔除没有获取到图片的和没有对应mn编号的
    camera_list = [item for item in camera_list if item.get(
        "capture") and item.get("mn")]

    print(camera_list)

    for model in action_ai.list_model():
        # 随机获取AI服务器
        random_int = 0
        if len(ai_analysis_servers) > 1:
            random_int = random.randint(0, len(ai_analysis_servers) - 1)

        aas = ai_analysis_servers[random_int]

        curr_time = datetime.datetime.now().date().strftime("%Y%m%d")

        # 构建文件夹名称
        floder_path = f"{model.code}-{curr_time}-{tool_id.gen_id()}"

        # 构建服务器路径
        remote_path = f"D:/ai-server-async-file-path/{floder_path}"

        curr_model_cameras = [
            item for item in camera_list if model.code in item.get("models")]

        if len(curr_model_cameras) < 1:
            continue

        # 获取对应模型的设备
        for camera in curr_model_cameras:
            # 构建文件名称
            img_name = f"{camera.get('mn')}-{camera.get('code')}-{camera.get('datetime')}-{model.code}-image.jpg"
            # 构建对应设备的名称及进行文件推送
            tool_log.info(
                f"推送文件{camera.get('capture')}到{remote_path}/{img_name}")
            tool_ssh.send_file(lj_bean_conn.BeanConn(aas.uri, aas.ftp_username, aas.ftp_password,
                               aas.ftp_port), camera.get("capture"), f"{remote_path}/{img_name}")

            ai_record_action.sync({
                "point_code": camera.get("mn"),
                "camera_index_code": camera.get('code'),
                "file_name": img_name,
                "ai_mode_type": model.code,
                "analytics_time": camera.get('datetime'),
                "file_type": "img"
            })

         # 调用AI服务器分析
        action_ai_remote.init(aas.uri).analyse(
            model.port_normal, remote_path, model.code)

    for camera in camera_list:
        # 删除本地文件
        os.remove(camera.get("capture"))


job()
# tool_run.do(job, 60 * 2)
# tool_run.start()
